import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.util.Random;

public class Peer {

	public static String readValueFromCommmandLine() {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String value = null;
		byte[] bArray = new byte[1024];
		try {
			value = br.readLine();
		} catch (IOException ioe) {
			ioe.printStackTrace();
			System.exit(1);
		}
		return value;
	}

	public static void main(String[] args) throws Exception {
		ReqPro rp = new ReqPro();

		String characters = "abcdefghijklmnopqrstuvwxyz";
		char[] text = new char[8];
		Random random = new Random();
		for (int i = 0; i < 8; i++) {
			text[i] = characters.charAt(random.nextInt(characters.length()));
		}
		PeerData.myName = new String(text);
		System.out.println("My Name is : " + PeerData.myName);

		ListeningService ls = new ListeningService();
		Thread listen = new Thread(ls);
		listen.start();

		SendingService ss = SendingService.getSendingService();
		try {
			String callerName = args[0];
			int callerLisPort = Integer.parseInt(args[1]);
			int callerSendPort = Integer.parseInt(args[2]);
			rp.addNeighbour(callerName, callerLisPort, callerSendPort,
					InetAddress.getLocalHost());
			rp.sendAddMeRequest(PeerData.myName, ls.portNum, ss.sendingPort,
					InetAddress.getLocalHost(), callerLisPort,
					InetAddress.getLocalHost());
		} catch (ArrayIndexOutOfBoundsException aiobe) {
			System.out.println("First Node Created");
		}
		boolean hasToRun = true;
		while (hasToRun) {

			System.out.println("\nChoose option for : " + PeerData.myName);
			System.out.println("0: Who am I?");
			System.out.println("1: Spawn");
			System.out.println("2: Leave");
			System.out.println("3: Neighbours");
			System.out.println("4: Send Message");
			System.out.println("5: Add Manually");
			String option = null;
			option = readValueFromCommmandLine();
			try {
				int choice = Integer.parseInt(option);
				switch (choice) {
				case 0:
					System.out.println("------------------------");
					System.out.println("Node Name: " + PeerData.myName);
					System.out.println("------------------------");
					break;
				case 1:

					System.out.println("How many peer to spawn?");
					int noOfPeers = Integer.parseInt(readValueFromCommmandLine().trim());

					for (int i = 0; i < noOfPeers; i++) {

						String[] params = {
								"/home/prasanna/P2PLAB/Code/" + "./run.sh",
								PeerData.myName, "" + ls.portNum,
								"" + ss.sendingPort };
						// String command =
						// "konsole --noclose -e java -jar /home/ravi/Projects/Netbeans/Java/Peer/dist/Peer.jar "
						// + PeerData.myName + " " + ls.portNum + " " +
						// ss.sendingPort;
						// System.out.println("Command: " + command);
						// Runtime.getRuntime().exec(command);
						Runtime.getRuntime().exec(params);
					}
					break;
				case 2:
					// rp.sendReplacementsToAll();
					rp.sendBroadcastToAll();
					ls.stopListening();
					System.out.println(" Leaving the network, Bye Bye !!");
					hasToRun = false;
					break;

				case 3:
					System.out.println("-------------------------");
					System.out.print("Connected Nodes: ");
					for (Neighbour nbr : PeerData.neighboursList) {
						System.out.print(nbr.name + " ");
					}

					System.out.println("-------------------------");
					break;

				case 4:

					System.out.println("MESSAGE TO ?");

					for (Neighbour nbr : PeerData.neighboursList) {
						System.out.println(nbr.name);
					}
					System.out.println("______________________");

					String msgTo = readValueFromCommmandLine();

					System.out.println("MESSAGE:");
					String msg = readValueFromCommmandLine();

					rp.sendMessage(msgTo, msg);

					break;

				case 5:
					System.out.println("Enter the details of the node to add");

					Neighbour newnbr = new Neighbour();
					System.out.println("Name:");
					newnbr.name = readValueFromCommmandLine();

					System.out.println("Listening port:");
					newnbr.listPort = Integer
							.parseInt(readValueFromCommmandLine().trim());

					System.out.println("Send port");
					newnbr.sendPort = Integer
							.parseInt(readValueFromCommmandLine().trim());

					System.out.println("HOST");
					newnbr.ip = InetAddress
							.getByName(readValueFromCommmandLine().trim());

					PeerData.neighboursList.add(newnbr);

					rp.sendAddMeRequest(PeerData.myName, ls.portNum,
							SendingService.getSendingService().sendingPort,
							InetAddress.getLocalHost(), newnbr.listPort,
							newnbr.ip);
					break;
				default:
					System.out.println("Invalid option!!!");
					System.out.println("\nChoose option: ");
					System.out.println("0: Who am I?");
					System.out.println("1: Spawn");
					System.out.println("2: Leave");
					System.out.println("3: Neighbours");
					System.out.println("4: Send Message");
					System.out.println("5: Add Manually");
					break;
				}
			} catch (NumberFormatException nfe) {
				System.out.println("Invalid option!!!");
				System.out.println("\nChoose option: ");
				System.out.println("0: Who am I?");
				System.out.println("1: Spawn");
				System.out.println("2: Leave");
				System.out.println("3: Neighbours");
				System.out.println("4: Send Message");
				System.out.println("5: Add Manually");
			}
		}
	}
}
